package com.letfox.ad.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyun.oss.OSSClient;
import com.letfox.ad.model.ADColScre;
import com.letfox.ad.model.ADPhysicScreen;
import com.letfox.ad.model.ADScreenPlan;
import com.letfox.ad.model.ADScreenRelGroup;
import com.letfox.ad.model.ADSereenPlan;
import com.letfox.ad.model.ADServingMaterial;
import com.letfox.ad.model.ADTimeRangeStatistics;
import com.letfox.ad.model.OSSConstant;
import com.letfox.ad.model.ScreenContent;
import com.letfox.ad.model.UtilConstants;
import com.letfox.ad.service.ADPhysicScreenService;
import com.letfox.ad.service.ADScreenPlanService;
import com.letfox.ad.service.ADServingMaterialService;
import com.letfox.ad.service.AdScreenRelGroupService;
import com.letfox.ad.service.ColScreService;
import com.letfox.ad.service.relation.ADColScreService;
import com.letfox.ad.util.ADUtil;
import com.letfox.ad.util.OSSUtil;
import com.letfox.common.enums.ResponseEnum;
import com.letfox.common.model.ResultResponse;
import com.letfox.common.util.DateUtil;
import com.letfox.common.util.JacksonUtil;
import com.letfox.redis.service.impl.RedisCacheBaseImpl;
import com.letfox.user.service.AccountCacheService;

@Service
public class ColScreServiceImpl extends RedisCacheBaseImpl<Object>  implements ColScreService {

	@Autowired
	private ADColScreService adColScreService;
	@Autowired
	private AccountCacheService accountCacheService;
	@Autowired
	private ADServingMaterialService adServingMaterialService;
	@Autowired
	private RedisTemplate<String,String> redisTemplate;
	@Autowired
	private ADPhysicScreenService adPhysicScreenService;
	@Autowired
	private AdScreenRelGroupService adScreenRelGroupService;
	@Autowired
	private ADScreenPlanService adScreenPlanService;


//	static List<ADServingMaterial> materialList = null;
//	static int timer = 0;

//	@Override
//	public ResultResponse getColScreUrl(String request_json) throws Exception {
//		ResultResponse resultResponse = new ResultResponse();
//		ADServingMaterial material = null;
//		
//		if (materialList == null)
//			materialList = adColScreService.getMaterialList(request_json);
//		int size=materialList.size();
//		if(timer>=size){
//			timer=0;
//		}
//		
//		material = materialList.get(timer);
//		Map<String, String> map = new HashMap<String, String>();
//		map.put("msg_type", material.getAdMaterialType());
//		map.put("mater_url", material.getAdMaterialUrl());
//		JSONObject jsonObject = JSONObject.fromObject(map);
//		resultResponse.setData(jsonObject.toString());
//		if (timer < size) {
//			timer ++;
//		}
//		//查询屏幕金额
//		String unitPrice= adColScreService.selectPlanMoney(request_json);
//		//记录广告日志
//		recordClicks(request_json,unitPrice,material.getAdMaterialUrl(),material.getAdMaterialType(),material.getAdScreenPlanId());
//		return resultResponse;
//	}

	
	@Override
	public ResultResponse getColScreUrl(String request_json) throws Exception {
		ResultResponse resultResponse = new ResultResponse();
		String screenId=request_json;
		Map<String, String> physMap=null;
		String planId = null;
		String json=null;
		Object startTime=null;
		Object endTime=null;
		boolean bool=false;
		//开始时间
		startTime=redisTemplate.opsForValue().get(request_json+","+"STARTTIME");
		//结束时间
		endTime=redisTemplate.opsForValue().get(request_json+","+"ENDTIME");
		if (startTime==null || endTime==null) {
			String keyStarTime=request_json+","+"STARTTIME";
			String keyEndTime=request_json+","+"ENDTIME";
			//查询大屏幕时间区
			physMap=adColScreService.queryPhysicId(screenId);
			startTime=physMap.get("START_TIME");
			endTime= physMap.get("END_TIME");
			//开始和结束时间存储入redis
			redisTemplate.opsForValue().set(keyStarTime, startTime.toString());
			redisTemplate.opsForValue().set(keyEndTime, endTime.toString());
			//设置失效时间
			redisTemplate.expire(keyStarTime,  ScreenContent.REDISEXPIRE, TimeUnit.SECONDS);
			redisTemplate.expire(keyEndTime,  ScreenContent.REDISEXPIRE, TimeUnit.SECONDS);
		}
		bool=ADUtil.checkTimeFrame(startTime.toString(), endTime.toString());
		if (bool) {
			//查询redis是否存在key
        	bool=redisTemplate.hasKey(request_json);
        	//查询是redis是否存在素材
        	Long index=redisTemplate.opsForList().size(request_json);
        	if (bool && index>0) {
        		json=redisTemplate.opsForList().index(request_json, 0);
            	Long i=redisTemplate.opsForList().remove(request_json, 1, json);
            	System.out.println(i);
            	@SuppressWarnings("unchecked")
				Map<String, String> map=(Map<String, String>) JSON.parse(json);
            	//广告ID
            	planId=map.get("AD_SCREEN_PLAN_ID");
            	map.remove("AD_SCREEN_PLAN_ID");
            	json=JSON.toJSONString(map);
            	//查询屏幕金额
            	String unitPrice= adColScreService.selectPlanMoney(request_json);
            	//记录广告日志
            	recordClicks(request_json,unitPrice,map.get("AD_MATERIAL_URL"),map.get("AD_MATERIAL_TYPE"),planId);
			}else {
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("screenId", request_json);
				map.put("value", 1);
				List<Map<String, String>> maps=adServingMaterialService.queryWithinMaterial(map);
				if (maps!=null && maps.get(0).size()>0) {
					json=JSON.toJSONString(maps.get(0));
				}else{
					json="{\"ret\":\"2\",\"msg\":\"无数据返回\"}";
				}
			}
		}else {
			json="{\"ret\":\"3\",\"msg\":\"不在屏幕运营时间内,无法播放广告\"}";
		}
        resultResponse.setData(json);
		return resultResponse;
	}
	
	@SuppressWarnings("deprecation")
	@Transactional(rollbackFor = Exception.class) 
	public ResultResponse insertAdScreen(ADColScre adColScre) throws Exception {
		ResultResponse resultResponse=new ResultResponse();
		List<MultipartFile> listObject=null;
		List<String> listType=null;
		OSSClient ossClient=null;
		String url=null;
		List<String> objectList=null;
		String fileName=null;
		MultipartFile multipartFile=null;
		String type=null;
		SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd"); 
		ADServingMaterial adServingMaterial=new ADServingMaterial();
		//广告文件名
		String adMaterialName=adColScre.getScreen_plan_name();
		if (adMaterialName.length()>40) {
			adMaterialName=adMaterialName.substring(0,40);
		}
		//存储广告信息
		ADScreenPlan adScreenPlan=new ADScreenPlan();
		adScreenPlan.setAdScreenPlanId(UUID.randomUUID().toString());
		adScreenPlan.setAdScreenPlanName(adMaterialName);
		adScreenPlan.setStartTime(formatter.parse(adColScre.getStart_date()));
		adScreenPlan.setEndTime(formatter.parse(adColScre.getEnd_date()));
		adScreenPlan.setDeleted("0");
		adScreenPlan.setAuditRemark(adColScre.getAd_desc());
		adScreenPlanService.insert(adScreenPlan);
		try {			
			//存储广告素材
			if(adColScre.getMater_obj_1()!=null||adColScre.getMater_obj_2()!=null||adColScre.getMater_obj_3()!=null){
				listObject=new ArrayList<MultipartFile>();
				listType=new ArrayList<String>();
				ossClient=OSSUtil.getInstance();	
				objectList=new ArrayList<String>();
				//广告素材存入list
				listObject.add(adColScre.getMater_obj_1());
				listObject.add(adColScre.getMater_obj_2());
				listObject.add(adColScre.getMater_obj_3());
				//广告素材类型存入list
				listType.add(ADUtil.getType(adColScre.getMater_type_1()));
				listType.add(ADUtil.getType(adColScre.getMater_type_2()));
				listType.add(ADUtil.getType(adColScre.getMater_type_3()));
				BufferedImage image;
				for (int i = 0; i < listObject.size(); i++) {
					multipartFile=listObject.get(i);			      
					if(multipartFile==null)
						continue;
					type=listType.get(i);
					InputStream inputStream=multipartFile.getInputStream();
					if (type.equals("1")) {
						image = ImageIO.read(inputStream);
						//长
						adServingMaterial.setHeight(image.getHeight());
						//宽
						adServingMaterial.setWidth(image.getWidth());
					}else if (type.equals("2")) {
//						CommonsMultipartFile cf= (CommonsMultipartFile)multipartFile; 
//					    DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
//					    File f = fi.getStoreLocation();
//						it.sauronsoftware.jave.Encoder encoder = new Encoder();
//						ADUtil.getFiledome(f);;
//				        MultimediaInfo m = encoder.getInfo(f);
//				        System.out.println("-------"+m.getDuration());
//				        long ls = m.getDuration()/1000;
//				        int hour = (int) (ls/3600);
//				        int minute = (int) (ls%3600)/60;
//				        int second = (int) (ls-hour*3600-minute*60);
				        //视频时长
//				        adServingMaterial.setPlaySeconds(Integer.parseInt(adColScre.getDuration()));
//				        System.out.println("此视频高度为:" + m.getVideo().getSize().getHeight());
//				        System.out.println("此视频宽度为:" + m.getVideo().getSize().getWidth());
					}
					fileName=ADUtil.getRandomFileName(multipartFile.getOriginalFilename());
					//将广告素材上传至阿里云OSS
					OSSUtil.ossUpload(ossClient, inputStream, fileName);
					//设置访问权限
					OSSUtil.ossFileACL(ossClient, OSSConstant.IMAGES+fileName, OSSConstant.PUBLIC_READ);
					objectList.add(OSSConstant.IMAGES+fileName);
					//返回URL
					url=OSSConstant.OSSHTTPS+fileName;
					//添加至数据库
					//唯一标示
					adServingMaterial.setAdMaterialId(UUID.randomUUID().toString());
					//素材名
					adServingMaterial.setAdMaterialName(multipartFile.getOriginalFilename());
					//素材类型
					adServingMaterial.setAdMaterialType(type);
					adServingMaterial.setAdMaterialUrl(url);
					//创建时间
					adServingMaterial.setCreateTime(new Date());
					//修改时间
					adServingMaterial.setUpdateTime(new Date());
					//创建人
					adServingMaterial.setCreateBy(UtilConstants.ACCOUNT);
					//修改人
					adServingMaterial.setUpdateBy(UtilConstants.ACCOUNT);
					adServingMaterial.setDel("0");
					adServingMaterialService.insert(adServingMaterial);
					//广告素材关联
					Map<String, String> planrlMap=new HashMap<String, String>();
					planrlMap.put("adScreenPlanId",adScreenPlan.getAdScreenPlanId());
					planrlMap.put("adMaterId", adServingMaterial.getAdMaterialId());
					planrlMap.put("deleted", "0");
					planrlMap.put("screenPlanId",adScreenPlan.getAdScreenPlanId());
					adColScreService.insertScrePlanMaterial(planrlMap);
					//机构广告关联
					ADScreenRelGroup adScreenRelGroup=new ADScreenRelGroup();
					adScreenRelGroup.setGroupId(UtilConstants.GROUPID);
					adScreenRelGroup.setScreenId(adScreenPlan.getAdScreenPlanId());
					adScreenRelGroup.setCreateTime(new Date());
					adScreenRelGroup.setUpdateTime(new Date());
					adScreenRelGroup.setCreateBy(UtilConstants.ACCOUNT);
					adScreenRelGroup.setUpdateBy(UtilConstants.ACCOUNT);
					adScreenRelGroupService.insert(adScreenRelGroup);
				}
				resultResponse.setStatusCode(ResponseEnum.R200.getCode());
				resultResponse.setStatusMessage(ResponseEnum.R200.getMessage());
				String response_json="{\"ret_code\": \"200\",\"ret_code\": \"保存成功\"}";
				resultResponse.setData(response_json);	
			}
		} catch (Exception e) {
			if(objectList!=null && objectList.size()>0)
				OSSUtil.ossDelete(ossClient, objectList);
			//关闭OSS连接池
		    ossClient.shutdown();
			throw new Exception("erro",e);	
		}
		//关闭OSS连接池
	    ossClient.shutdown();
		return resultResponse;
	}
	
	@Transactional(rollbackFor = Exception.class) 
	@Override
	public ResultResponse getNewPhysScreen(String request_json)
			throws Exception {
		request_json = new String(request_json.getBytes("ISO8859-1"), "UTF-8"); 
		ResultResponse resultResponse=new ResultResponse();
		String json=null;
		com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(request_json);
		ADPhysicScreen adPhysicScreen=new ADPhysicScreen();
		//屏幕ID
		String screenId=ADUtil.getPhysScreenID();
		adPhysicScreen.setScreenId(screenId);
		adPhysicScreen.setScreenName(jsonObject.getString("screen_name"));
		adPhysicScreen.setScreenAddressCode(jsonObject.getString("screen_address_code"));
		adPhysicScreen.setScreenAddress(jsonObject.getString("screen_address"));
		adPhysicScreen.setStartDate(DateUtil.parse(jsonObject.getString("start_date")));
		adPhysicScreen.setEndDate(DateUtil.parse(jsonObject.getString("end_date")));
		adPhysicScreen.setStartTime(DateUtil.parse(jsonObject.getString("start_time"),"HH:mm"));
		adPhysicScreen.setEndTime(DateUtil.parse(jsonObject.getString("end_time"),"HH:mm"));
		adPhysicScreen.setUnitPrice(new BigDecimal(jsonObject.getString("unit_price")));
		adPhysicScreen.setResLength(Integer.parseInt(jsonObject.getString("resolution_length")));
		adPhysicScreen.setResWidth(Integer.parseInt(jsonObject.getString("resolution_width")));
		adPhysicScreen.setSizeHeight(Float.parseFloat(jsonObject.getString("size_width")));
		adPhysicScreen.setSizeWidth(Float.parseFloat(jsonObject.getString("size_hetght")));
		String account=jsonObject.getString("account");
		adPhysicScreen.setCreateBy(UtilConstants.ACCOUNT);
		adPhysicScreen.setUpdateBy(UtilConstants.ACCOUNT);
		adPhysicScreen.setDeleted("0");
		//机构ID
		String group_id=jsonObject.getString("group_id");
		ADScreenRelGroup adScreenRelGroup=new ADScreenRelGroup();
		adScreenRelGroup.setScreenId(screenId);
		adScreenRelGroup.setGroupId(UtilConstants.GROUPID);
		adScreenRelGroup.setCreateTime(new Date());
		adScreenRelGroup.setUpdateTime(new Date());
		adScreenRelGroup.setCreateBy(UtilConstants.ACCOUNT);
		adScreenRelGroup.setUpdateBy(UtilConstants.ACCOUNT);
		adScreenRelGroup.setDel("0");
		try {
			int i=adPhysicScreenService.insert(adPhysicScreen);
			if (i<=0)
				throw new Exception("physic添加失败");
			adScreenRelGroupService.insert(adScreenRelGroup);
		} catch (Exception e) {
			json="{"+"\""+ResponseEnum.R500.getCode()+"\",\"保存失败\"}";
			resultResponse.setData(json);
			resultResponse.setStatusCode(ResponseEnum.R500.getCode());
			resultResponse.setStatusMessage(ResponseEnum.R500.getMessage());
			return resultResponse;
		}
		json="{"+"\""+ResponseEnum.R200.getCode()+"\",\"保存成功\"}";
		resultResponse.setData(json);
		resultResponse.setStatusCode(ResponseEnum.R200.getCode());
		resultResponse.setStatusMessage(ResponseEnum.R200.getMessage());
		return resultResponse;
	}
	
	/**
	 * 广告日志逻辑
	 */
	@Override
	public void recordClicks(String screenId, String unitPrice,String url,String adType,String adScreenPlanId)
			throws Exception {
		Map<String, String> map=new HashMap<String, String>();
		map.put("screenId", screenId);
		map.put("url", url);
		map.put("unitPrice", unitPrice);
		map.put("adType", adType);
		map.put("adScreenPlanId", adScreenPlanId);
		//记录广告播放次数
		adColScreService.insertScreenPlayDetail(map);
	}

	@Override
	public ResultResponse censusScreenAd(String request_json) throws Exception {
		ResultResponse resultResponse=new ResultResponse();
		JSONObject jsonObject = JSONObject.fromObject(request_json);
		Map<String, String> map=new HashMap<String, String>();
		map.put("start_date", jsonObject.getString("start_date"));
		map.put("end_date", jsonObject.getString("end_date"));
		map.put("screen_id", jsonObject.getString("screen_id"));
		//组装JSON集合
		Map<String, Object> jsonMap=new HashMap<String, Object>();
		//统计当日，当月播放次数和金额总
		Map<String, String> screMap=adColScreService.selectAdCurrent(map);
		//统计查询起止时间范围内的每天的播放次数
		List<ADTimeRangeStatistics> todayList= adColScreService.selectAdEveryday(map);
		//当日最近十次播放的记录
		List<Map<String, String>> firstTenList=adColScreService.selectAdFirstTen(jsonObject.getString("screen_id"));
		//响应码
		jsonMap.put("ret_code", ResponseEnum.R200.getCode());
		jsonMap.put("ret_msg", "访问成功");
		//当日,当月总次数
		jsonMap.put("data", screMap);
		//时间范围内每天的播放次数
		jsonMap.put("census_list", todayList);
		//最近10条广告记录
		jsonMap.put("detail_list", firstTenList);
		//组装JSON字符串
		JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
		String json =JSON.toJSONString(jsonMap, SerializerFeature.WriteDateUseDateFormat); 
		resultResponse.setData(json);
		resultResponse.setStatusCode(ResponseEnum.R200.getCode());
		resultResponse.setStatusMessage(ResponseEnum.R200.getMessage());
		return resultResponse;
	}

	@Override
	public String getPhysName() throws Exception {
		List<Map<String, String>> list=adColScreService.selectPhys();
		String json = JacksonUtil.toJson(list);
		return json;
	}

	@Override
	public String getAllADPlan() throws Exception {
		List<Map<String, String>> jsonMap=adColScreService.selectADPlans();
		String json = JacksonUtil.toJson(jsonMap);
		return json;
	}

	@Override
	public ResultResponse getAdRecord(String request_json) throws Exception {
		ResultResponse resultResponse=new ResultResponse();
		JSONObject jsonObject = JSONObject.fromObject(request_json);
		Map<String, String> map=new HashMap<String, String>();
		map.put("start_date", jsonObject.getString("start_date"));
		map.put("end_date", jsonObject.getString("end_date"));
		map.put("screenPlanId", jsonObject.getString("screen_plan_id"));
		map.put("groupId", jsonObject.getString("groupId"));
		//组装JSON集合
		Map<String, Object> jsonMap=new HashMap<String, Object>();
		//统计广告当日，当月播放次数和金额总
		Map<String, String> screMap=adColScreService.selectAdCurrent(map);
		//统计查询起止时间范围内的广告每天的播放次数
		List<ADTimeRangeStatistics> todayList= adColScreService.selectAdEveryday(map);
		Map<String, String> map2=new HashMap<String, String>();
		map2.put("screenPlanId", jsonObject.getString("screen_plan_id"));
		map2.put("groupId", jsonObject.getString("groupId"));
		//广告当日最近十次播放的记录
		List<Map<String, String>> firstTenList=adColScreService.selectAdPhysicTen(map2);
		//响应码
		jsonMap.put("ret_code", ResponseEnum.R200.getCode());
		jsonMap.put("ret_msg", "访问成功");
		//广告当日,当月总次数
		jsonMap.put("data", screMap);
		//时间范围内广告每天的播放次数
		jsonMap.put("census_list", todayList);
		//最近10条广告记录
		jsonMap.put("detail_list", firstTenList);
		//组装JSON字符串
		JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
		String json =JSON.toJSONString(jsonMap, SerializerFeature.WriteDateUseDateFormat); 
		resultResponse.setData(json);
		resultResponse.setStatusCode(ResponseEnum.R200.getCode());
		resultResponse.setStatusMessage(ResponseEnum.R200.getMessage());
		return resultResponse;
	}

	@Override
	public ResultResponse queryPlanList(String request_json) throws Exception {
		ResultResponse resultResponse=new ResultResponse();
		JSONObject jsonObject = null;
		Map<String, String> requestMap= new HashMap<String, String>();
		//组装sql查询条件
		if(request_json!=null&&request_json!=""){
			jsonObject=JSONObject.fromObject(request_json);
			String adName=jsonObject.getString("adName");
			if(adName!=null&&adName!=""){
				requestMap.put("adName",adName );
			}
			requestMap.put("start_date", jsonObject.getString("start_date"));
			requestMap.put("end_date", jsonObject.getString("end_date"));
			
		}
		//查询广告信息
		List<Map<String, String>> jsonList=adColScreService.queryPlanList(requestMap);
		//组装JSON字符串
		JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
		String json =JSON.toJSONString(jsonList, SerializerFeature.WriteDateUseDateFormat); 
		resultResponse.setData(json);
		resultResponse.setStatusCode(ResponseEnum.R200.getCode());
		resultResponse.setStatusMessage(ResponseEnum.R200.getMessage());
		return resultResponse;
	}

	@Override
	public ResultResponse queryScreenInfo(String screenPlanId)throws Exception {
		ResultResponse resultResponse=new ResultResponse();
		Map<String, Object> map=new HashMap<String, Object>();
		Map<String, String> planMap=adColScreService.queryPlan(screenPlanId);
		map.put("plan", planMap);
		//根据广告ID查询广告信息
	    List<Map<String, String>>  listMap=adColScreService.queryScreenInfo(screenPlanId);
	    map.put("planInfo", listMap);
	    //组装JSON
	    JSON.DEFFAULT_DATE_FORMAT = "HH:mm:ss";
		String json =JSON.toJSONString(map, SerializerFeature.WriteDateUseDateFormat); 
		resultResponse.setData(json);
		resultResponse.setStatusCode(ResponseEnum.R200.getCode());
		resultResponse.setStatusMessage(ResponseEnum.R200.getMessage());
		return resultResponse;
	}

	@Transactional(rollbackFor = Exception.class) 
	public ResultResponse updateScreenInfo(String request_json)throws Exception {
		ResultResponse resultResponse=new ResultResponse();
		//解析JSON字符串
		JSONObject jsonObject = JSONObject.fromObject(request_json);
		JSONArray materialObject=JSONArray.parseArray(jsonObject.getString("materialArray"));
		JSONObject planJson = JSONObject.fromObject(jsonObject.getString("planMap"));
		for (int i = 0; i < materialObject.size(); i++) {
			JSONObject  materialJson = JSONObject.fromObject(materialObject.get(i));
			//广告素材信息
			ADServingMaterial adServingMaterial=new ADServingMaterial();
			adServingMaterial.setAudit(materialJson.getString("materialAudit"));
			adServingMaterial.setAuditRemark(materialJson.getString("materialRemark"));
			adServingMaterial.setAdMaterialId(materialJson.getString("divId"));
			//修改素材信息
			adServingMaterialService.updateByPrimaryKeySelective(adServingMaterial);
		}
		//广告信息
		ADSereenPlan adSereenPlan=new ADSereenPlan();
		adSereenPlan.setAdSereenPlanId(planJson.getString("planId"));
		adSereenPlan.setAudit(planJson.getString("planAudit"));
		adSereenPlan.setAudit_remark(planJson.getString("planRemark"));
		//修改广告信息
		adColScreService.updatePlanInfo(adSereenPlan);
		String json="{"+"\""+ResponseEnum.R200.getCode()+"\",\"保存成功\"}";
		resultResponse.setData(json);
		resultResponse.setStatusCode(ResponseEnum.R200.getCode());
		resultResponse.setStatusMessage(ResponseEnum.R200.getMessage());
		return resultResponse;
	}


	public void writeRedisJob() throws Exception {
		List<Map<String, String>> list=adColScreService.queryPhysicIdAll();
		String key=null;
		String keyStarTime=null;
		String keyEndTime=null;
		Object startTime=null;
		Object endTime=null;
		double percent=0;
		int within=0;
		int abroad=0;
		String materJson=null;
		List<Map<String, String>> listWithinMaps=null;
		List<Map<String, String>> listAbroadMaps=null;
		Map<String, Object> materialMap=new HashMap<String, Object>();
		List<String> listWithinJson=new ArrayList<String>();
		List<String> listAbroadJson=new ArrayList<String>();
		for (Map<String, String> map : list) {
			key=map.get("SCREEN_ID");
			keyStarTime=key+","+"STARTTIME";
			keyEndTime=key+","+"ENDTIME";
			startTime=map.get("START_TIME");
			endTime= map.get("END_TIME");
			if (redisTemplate.hasKey(key) && redisTemplate.opsForList().size(key)>0) {
				redisTemplate.opsForValue().set(keyStarTime,startTime.toString() );
				redisTemplate.opsForValue().set(keyEndTime,endTime.toString());
			}else {
				percent=Double.parseDouble(map.get("PERCENT"));
				abroad=(int) (percent*20);
				within=20-abroad;		
				int x=0;
				//查询条件
				materialMap.put("screenId", key);
				materialMap.put("value", within);
				//查询广告主内播素材
				listWithinMaps=adServingMaterialService.queryWithinMaterial(materialMap);
				for (Map<String, String> map2 : listWithinMaps) {
					materJson=JSON.toJSONString(map2);
					listWithinJson.add(materJson);
				}
				//如果数量不足循环补充 
				if (listWithinJson.size()!=0) {
					for (int i = listWithinJson.size(); i < within; i++) {
						listWithinJson.add(listWithinJson.get(x));
						x++;
					}
				}
				if (abroad>0) {
					//设置时间格式
					SimpleDateFormat sDateFormat=new SimpleDateFormat("HH:mm:ss"); 
					//当前时间
				    String systemTime=sDateFormat.format(new Date());
					materialMap.put("value", abroad);
					materialMap.put("materialMap", systemTime);
					materialMap.put("endTime", systemTime);
					//查询广告主外播素材
					listAbroadMaps=adServingMaterialService.queryWithinMaterial(materialMap);
					for (Map<String, String> map2 : listAbroadMaps) {
						materJson=JSON.toJSONString(map2);
						listAbroadJson.add(materJson);
					}
					x=0;
					//如果数量不足循环补充 
					if (listAbroadJson.size()!=0) {
						for (int i = listAbroadJson.size(); i < abroad; i++) {
							listAbroadJson.add(listAbroadJson.get(x));
							x++;
						}
					}
				}
				x=0;
				listWithinJson.addAll(listAbroadJson);
				if (listWithinJson.size()!=0 && listWithinJson.size()<20) {
					for (int i = listWithinJson.size(); i < 20; i++) {
						listWithinJson.add(listWithinJson.get(x));
						x++;
					}
				}
				if (listWithinJson.size()>0) {
					redisTemplate.delete(key);
					redisTemplate.delete(keyStarTime);
					redisTemplate.delete(keyEndTime);						
					redisTemplate.opsForValue().set(keyStarTime, startTime.toString());
					redisTemplate.opsForValue().set(keyEndTime, endTime.toString());
					//将素材存入redis
					redisTemplate.opsForList().rightPushAll(key, listWithinJson);
					//设置redis有效时间
					redisTemplate.expire(key, ScreenContent.REDISEXPIRE, TimeUnit.SECONDS);
					redisTemplate.expire(keyStarTime,  ScreenContent.REDISEXPIRE, TimeUnit.SECONDS);
					redisTemplate.expire(keyEndTime,  ScreenContent.REDISEXPIRE, TimeUnit.SECONDS);
				}
				listWithinJson.clear();
				listAbroadJson.clear();
			}
		}
	}

	@Override
	public String writeRedisByScreID(String screen_id,Map<String, String> phyMap) throws Exception {	
		String json=null;
		//查询大屏幕时间区
		Map<String, String> map=phyMap;
		Object startTime=map.get("START_TIME");
		Object endTime= map.get("END_TIME");
		//查询广告素材
		List<ADServingMaterial> listMaterial=null;
		try {
			listMaterial=adServingMaterialService.queryMaterial(10);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
		List<String> listJson=new ArrayList<String>();
		String materJson=null;
		Map<String,Object> materialMap=new HashMap<String, Object>();
		for (ADServingMaterial adServingMaterial : listMaterial) {
			materialMap.put("msg_type", adServingMaterial.getAdMaterialType());
			materialMap.put("mater_url", adServingMaterial.getAdMaterialUrl());
			materialMap.put("play_seconds", adServingMaterial.getPlaySeconds());
			materJson=JSON.toJSONString(materialMap);
			listJson.add(materJson);
		}
		String key=screen_id;
		String keyStarTime=key+","+"STARTTIME";
		String keyEndTime=key+","+"ENDTIME";
	    json=listJson.get(0);
		listJson.remove(0);
		if (listJson.size()>0) {
			redisTemplate.delete(key);
			redisTemplate.delete(keyStarTime);
			redisTemplate.delete(keyEndTime);
			redisTemplate.opsForValue().set(keyStarTime, startTime.toString());
			redisTemplate.opsForValue().set(keyEndTime, endTime.toString());
			//将素材存入redis
			redisTemplate.opsForList().rightPushAll(key, listJson);
			//设置redis有效时间
			redisTemplate.expire(key, 1800, TimeUnit.SECONDS);
			redisTemplate.expire(keyStarTime, 1800, TimeUnit.SECONDS);
			redisTemplate.expire(keyEndTime, 1800, TimeUnit.SECONDS);
		}
		@SuppressWarnings("unchecked")
		Map<String, String> jsonMap=(Map<String, String>) JSON.parse(json);
		jsonMap.remove("AD_SCREEN_PLAN_ID");
		json=JSON.toJSONString(jsonMap);
		return json;
	}
	
}
